package me.leiusual.sharing.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_shop_business_apply.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.BusinessApply
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.shop.adapter.ShopBusinessApplyParentAdapter
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-30
 * description:
 */
class ShopBusinessApplyFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: ShopBusinessApplyViewModel by viewModels { factory }

  private val args: ShopBusinessApplyFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_shop_business_apply, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = ShopBusinessApplyParentAdapter {
      doUpdateState()
    }

    check_box.setOnClickListener(this)
    button_confirm.setOnClickListener(this)

    observeData()
    viewModel.businessCondition(args.type, args.level)
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.check_box -> {
        doUpdateState(check_box.isChecked)
      }
      R.id.button_confirm -> {
        doConfirm()
      }
    }
  }

  private fun observeData() {
    viewModel.businessCondition.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("businessCondition = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          val adapter = recycler_view.adapter as ShopBusinessApplyParentAdapter
          adapter.submitList(it.data.purchaseConditions)
        }
      }
    })

    viewModel.businessApply.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("businessApply = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_confirm.isEnabled = true

          // 去订单确认页面支付
          val mutableMap = mutableMapOf<Long, Int>()
          it.data.forEach { response ->
            mutableMap[response.cartId] = response.quantity
          }
          val args = Bundle()
          args.putSerializable("cartIdQuantity", mutableMap as HashMap)
          findNavController().navigate(R.id.action_shopBusinessApplyFragment_to_cartOrderFragment, args)
        }
      }
    })
  }

  /**
   * 执行更新状态
   * @param selectedAll 是否全选
   */
  private fun doUpdateState(selectedAll: Boolean? = null) {

    // 是否有数据
    val data = viewModel.businessCondition.value as? Data.Success
    if (data != null) {

      // 是否全选
      if (selectedAll != null) {
        data.data.purchaseConditions.forEach { purchaseCondition ->
          purchaseCondition.productOptions.forEach { productOption ->
            if (productOption.canModified) {
              productOption.checked = selectedAll
            }
          }
        }
      }

      // 刷新列表
      recycler_view.adapter?.notifyDataSetChanged()

      // 计算合计
      var totalRmb = 0.0
      var totalJfb = 0.0
      data.data.purchaseConditions.forEach { purchaseCondition ->
        purchaseCondition.productOptions.forEach { productOption ->
          if (productOption.checked!!) {
            totalRmb += productOption.coinAmount * productOption.amount!!
            totalJfb += productOption.pointCoins * productOption.amount!!
          }
        }
      }
      val size = 10f.spToPx(requireContext())
      val builder = StringBuilder()
      builder.append("""<font color="red">合计：""")
      builder.append("""<size_$size>￥</size_$size>""")
      builder.append(totalRmb)
      if (totalJfb > 0) {
        builder.append("""  <size_$size>分</size_$size>""")
        builder.append(totalJfb)
      }
      builder.append("""</font>""")
      text_view_total.text = builder.toString().toSpanned()
    }
  }

  /**
   * 去结算
   */
  private fun doConfirm() {

    // 是否有数据
    val data = viewModel.businessCondition.value as? Data.Success
    if (data != null) {

      // 获取选中的商品
      val list = mutableListOf<BusinessApply.Request.SelectedProduct>()
      data.data.purchaseConditions.forEach { purchaseCondition ->
        Timber.v("purchaseCondition = %s", purchaseCondition)

        val selectedProductMap = mutableMapOf<Long, Int>()
        purchaseCondition.productOptions.forEach { productOption ->
          Timber.v("productOption = %s", productOption)
          if (productOption.checked!!) {
            selectedProductMap[productOption.id] = productOption.amount!!
          }
        }

        if (selectedProductMap.isNotEmpty()) {
          val selectedProduct = BusinessApply.Request.SelectedProduct(
              purchaseCondition.conditionName,
              selectedProductMap,
              purchaseCondition.storeBusinessInfo.storeId,
              purchaseCondition.storeBusinessInfo.storeId
          )
          list.add(selectedProduct)
        }
      }

      // 检查有没有选中的商品
      if (list.isEmpty()) {
        toast("您还没有选择商品哦")
        return
      }

      // 提交订单
      val request = BusinessApply.Request(
          args.level,
          args.type,
          list,
          viewModel.store.currentStoreId
      )
      viewModel.businessApply(request)
    }
  }
}